﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.IdentityModel.Claims;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls;
using Veracruz.Facebook.IdentityModel;

namespace Veracruz.Facebook.Sharepoint.Webparts
{
    public sealed class RegisterEmail
        : WebPart
    {
        protected override void CreateChildControls()
        {
            if (ClaimsPrincipal.Current.Identities.Count > 0 && ClaimsPrincipal.Current.Identity.IsAuthenticated)
            {
                //Claim __emailClaim = ClaimsPrincipal.Current.Identities[0].Claims.Single<Claim>(claim => claim.ClaimType == System.IdentityModel.Claims.ClaimTypes.Email);
                if (String.IsNullOrEmpty(ClaimsPrincipal.Current.Identities[0].Claims.Single<Claim>(claim => claim.ClaimType == System.IdentityModel.Claims.ClaimTypes.Email).Value))
                {
                    TextBox __email = new TextBox();
                    __email.ID = "__email";
                    Button __validate = new Button();
                    __validate.Text = "Register email";
                    __validate.Click += new EventHandler(RegisterEmail_Click);

                    this.Controls.Add(__email);
                    this.Controls.Add(__validate);

                }
                else
                {
                    Button __remove = new Button();
                    __remove.Text = "Unregister email";
                    __remove.Click += new EventHandler(Unregister_Click);

                    this.Controls.Add(__remove);
                }
            }
            else
            {
                Label __label = new Label();
                __label.Text = "You are not logged in";
                this.Controls.Add(__label);
            }

            base.CreateChildControls();
        }

        void Unregister_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(ClaimsPrincipal.Current.Identities[0].Claims.Single<Claim>(claim => claim.ClaimType == System.IdentityModel.Claims.ClaimTypes.Email).Value))
            {

            }
        }

        void RegisterEmail_Click(object sender, EventArgs e)
        {
            TextBox __email = this.FindControl("__email") as TextBox;
            if (__email != null && !String.IsNullOrEmpty(__email.Text))
            {
                IClaimsIdentity l_identity = ClaimsPrincipal.Current.Identity as IClaimsIdentity;
                if (l_identity != null)
                {
                    Session l_session = l_identity.GetSession();
                    FacebookHelper.Register(l_session, __email.Text);
                }
            }
        }
    }
}
